package com.github.defense.plugin.gray.decision.factory;

import com.github.defense.plugin.gray.decision.GrayDecision;
import com.github.defense.plugin.gray.request.GrayHttpRequest;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 基于请求方法做参数校验
 *
 * @Author: lettger
 * @Date: 2021/6/23 10:57 上午
 */
@Slf4j
public class MethodGrayDecisionFactory extends AbstractGrayDecisionFactory<MethodGrayDecisionFactory.Config> {

    public MethodGrayDecisionFactory() {
        super(Config.class);
    }

    @Override
    public GrayDecision apply(Config config) {
        return args -> {
            log.debug("Method Config:{}", config);
            GrayHttpRequest request = (GrayHttpRequest) args;
            String method = request.getMethod();
            if (StringUtils.isEmpty(method) || StringUtils.isEmpty(config.getMethod())) {
                return false;
            }
            return config.getStrategy().compare(method.toLowerCase(), config.getMethod().toLowerCase());
        };
    }

    @Setter
    @Getter
    @ToString
    public  static class Config extends AbstractGrayStrategyFactory.Strategy {
        private String method;
    }
}
